package com.sxj.corejava.code15_反射;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author 石小俊
 */
public class Test05_操作方法 {

    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Class c = User.class;

        System.out.println("***********************获取当前类以及其祖先类中所有public修饰的方法***********************");
        Method[] methods = c.getMethods();
        for (Method method : methods) {
            System.out.println(method);
        }

        System.out.println("***********************获取当前类中所有的方法,不区分修饰符***********************");
        Method[] declaredMethods = c.getDeclaredMethods();
        for (Method declaredMethod : declaredMethods) {
            System.out.println(declaredMethod);
        }

        System.out.println("***********************获取当前类以及其祖先类中指定的public修饰的方法***********************");
        Method showMethod = c.getMethod("show");
        System.out.println(showMethod);
        Method addMethod = c.getMethod("add", int.class, int.class);
        System.out.println(addMethod);

        System.out.println("***********************获取当前类中指定的方法,不区分修饰符***********************");
        Method testMethod = c.getDeclaredMethod("test");
        System.out.println(testMethod);

        System.out.println("***********************操作方法***********************");
        System.out.println("方法名:" + testMethod.getName());
        System.out.println("方法名:" + showMethod.getName());

        System.out.println("***********************执行方法***********************");
        User user = new User();
        showMethod.invoke(user);
        testMethod.setAccessible(true);
        testMethod.invoke(user);
        Object result = addMethod.invoke(user, 1, 2);
        System.out.println("1+2=" + result);
    }
}
